<script src='websocket_connection.js'></script>
<script>

// This page has two modes, one where the websocket connection lives in the
// document context, and one where it lives in a worker. This is encoded by the
// presence (or absence) of an URL param named 'inWorker'.
let eventTarget;
let worker;
if (new URL(location).searchParams.get('inWorker')) {
  worker = new Worker('websocket_worker.js');
  eventTarget = worker;
} else {
  eventTarget = window;
}

function connectWebSocket(url) {
  // Listens for 'onmessage' or 'onclose' messages from the websocket, and sends
  // them to the test fixture.
  const connectionPromise = new Promise(resolve => {
    eventTarget.addEventListener('message', (e) => {
      if (e.data == 'onmessage') {
        resolve(true);
      } else if (e.data == 'onclose') {
        resolve(false);
      }
    });
  });

  if (worker) {
    worker.postMessage({url: url});
  } else {
    var messageCallback = (data) => { self.postMessage(data, location); }
    connectWebSocketWithMessageCallback(url, messageCallback);
  }

  return connectionPromise;
}
</script>
